<template>
  <a-modal
    v-model:visible="visible"
    draggable
    width="680px"
    @before-ok="handleBeforeOk"
    @cancel="handleChangeVisible"
    @close="close"
  >
    <template #title>
      {{
        formData.id
          ? `${$t('columns.operations.edit')}`
          : `${$t('searchTable.operation.create')}`
      }}公告</template
    >
    <a-form
      ref="formRef"
      :model="formData"
      class="form"
      :label-col-props="{ span: 6 }"
      :wrapper-col-props="{ span: 18 }"
    >
      <a-form-item
        field="title"
        label="标题"
        :rules="[{ required: true, message: '请输入标题' }]"
      >
        <a-input v-model="formData.title" placeholder="请输入标题" />
      </a-form-item>

      <a-form-item
        field="text"
        label="内容"
        :rules="[{ required: true, message: '请输入内容' }]"
      >
        <a-textarea
          v-model="formData.text"
          placeholder="请输入内容"
          :auto-size="{
            minRows: 3,
            maxRows: 5,
          }"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import {
    AnnouncementVO,
    createAnnouncement,
    updateAnnouncement,
  } from '@/api/announcement-management';

  const formRef = ref();
  const visible = ref(false);
  const form = () => {
    return {
      id: '',
      text: '',
      title: '',
    };
  };
  const formData = ref(form());
  const handleChangeVisible = (obj: AnnouncementVO) => {
    visible.value = !visible.value;
    if (!visible.value) formData.value = form();
    if (visible.value && obj) formData.value = JSON.parse(JSON.stringify(obj));
  };
  const close = () => {
    visible.value = false;
    formData.value = form();
    formRef.value.clearValidate();
  };

  const emit = defineEmits(['refresh']);

  function handleBeforeOk(done: any) {
    formRef.value.validate((valid: any) => {
      if (valid) {
        done(false);
      } else if (formData.value.id) {
        updateAnnouncement(formData.value)
          .then(() => {
            Message.success('操作成功');
            emit('refresh');
            done();
          })
          .catch(() => {
            done(false);
          });
      } else {
        createAnnouncement(formData.value)
          .then(() => {
            Message.success('操作成功');
            emit('refresh');
            done();
          })
          .catch(() => {
            done(false);
          });
      }
    });
  }

  defineExpose({ handleChangeVisible });
</script>
